﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.DBUtility;
using Newtonsoft.Json;
using UFC.Common;
using System.Net;
using System.Collections;
using Newtonsoft.Json.Converters;
using System.IO;
using System.Configuration;
using System.Threading.Tasks;
using System.Web;

namespace SendIndustrialNetwork
{
    public class pushTableDataToDC
    {
        public string dataCenterHost = ConfigurationManager.AppSettings["dataCenterHost"].ToString();
        public string postUrl = "http://localhost:43844/api/Mms/hellopost";
        public string uploadUrl = "http://{0}:8080/lygkdc-service/lygk/dc/fileUploaddc";//文件上传地址
        public string tableDefurl = "http://{0}:8080/lygkdc-service/lygk/dc/pushTableDefToDC";//表结构上传地址
        public string tableDataUrl = "http://{0}:8080/lygkdc-service/lygk/dc/pushDataToDC";//表数据上传地址
        public int perRows = Convert.ToInt32(ConfigurationManager.AppSettings["perRows"].ToString());
        public string getTableDefurl = "http://{0}:8080/lygkdc-service/lygk/dc/getTableDef";//表结构获取地址
        public string getTableDataUrl = "http://{0}:8080/lygkdc-service/lygk/dc/getTableData";//数据获取地址

        public string filePathUrl = ConfigurationManager.AppSettings["filePathUrl"].ToString();//工艺附件存储站点地址
        public string toDataCenterAppid = ConfigurationManager.AppSettings["ToDataCenterAppID"].ToString();//推送数据中心来源ID
        public string toAppId_rb = ConfigurationManager.AppSettings["ToAppID_RB"].ToString();//推送数据中心目的ID（热表）
        public string toAppId_gx = ConfigurationManager.AppSettings["ToAppID_GX"].ToString();//推送数据中心目的ID（管线）

        public static string rbFactoryID = ConfigurationManager.AppSettings["RbFactoryID"].ToString();//热表分厂ID
        public string mesPathUrl = ConfigurationManager.AppSettings["MesPathUrl"].ToString();//75地址
        public string qmsPathUrl = ConfigurationManager.AppSettings["QmsPathUrl"].ToString();//Qms理化附件地址

        EncryptHelper encryptHelper = new EncryptHelper();
        public pushTableDataToDC()
        {
            uploadUrl = String.Format(uploadUrl, dataCenterHost);//文件上传地址
            tableDefurl = String.Format(tableDefurl, dataCenterHost);//表结构上传地址
            tableDataUrl = String.Format(tableDataUrl, dataCenterHost);//表数据上传地址
            getTableDefurl = String.Format(getTableDefurl, dataCenterHost);//表结构获取地址
            getTableDataUrl = String.Format(getTableDataUrl, dataCenterHost);//数据获取地址
            LogHelp.SetConfig();
        }

        //文件上传
        public void ExcuteFile(String fileUrl, string fileUrl76, string toAppId, string bsType, string id, string fileMark = "")
        {
            //string fileUrl = "C:\\产线接口相关信息表.docx";
            try
            {
                string FileName = Path.GetFileName(fileUrl);
                Dictionary<string, string> bsdata = new Dictionary<string, string>();
                bsdata.Add("ID", id);
                bsdata.Add("FileName", FileName);
                bsdata.Add("FilePath", fileUrl76);
                if (!string.IsNullOrWhiteSpace(fileMark))
                {
                    bsdata.Add("mOMObjectNotes", fileMark);//传给热表工控网文件标识
                }
                HeadEntity head = new HeadEntity();
                head.FileName = fileUrl;//System.Web.HttpUtility.UrlEncode(fileUrl);//fileUrl
                head.Formappid = toDataCenterAppid;
                head.Toappid = toAppId;
                head.Bstype = bsType;
                head.WenJianQiCaoRen = "刘美美";
                head.QianFaRen = "刘美美";
                head.ShenPiRen = "刘美美";
                head.BsData = JsonConvert.SerializeObject(bsdata);
                LogHelp.WriteLog("文件 【" + fileUrl + "】开始上传");
                var result = HttpUtils.uploadFile(uploadUrl, head);
                LogHelp.WriteLog("文件上传返回结果：" + result);
                if (File.Exists(fileUrl) && bsType.Equals("sendfiles"))
                {
                    File.Delete(fileUrl);
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("【" + fileUrl + "】文件上传异常：" + ex.Message);
            }
        }

        public void DownloadFileFrom76(string fileUrl, string toAppId, string objectdocinfoid)
        {
            var absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\";
            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(absolutePath);
            }
            string fileNameWithExtension = Path.GetFileName(fileUrl);
            var path = absolutePath + fileNameWithExtension;
            //先从10.7.15.76文件服务器下载文件到本地，再上传给数据中心
            try
            {
                WebClient client = new WebClient();
                byte[] bytes = client.DownloadData(filePathUrl + HttpUtility.UrlEncode(fileUrl.Replace("Temp/", "")).Replace("+", "%20"));
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(bytes, 0, bytes.Length);
                }
                LogHelp.WriteLog("76原始地址【" + fileUrl + "】新地址：" + path);
                ExcuteFile(path, fileUrl, toAppId, "sendfiles", objectdocinfoid);
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("【" + fileUrl + "】文件下载异常：" + ex.Message);
                LogHelp.WriteOrcale("文件下载异常" + "@^" + fileNameWithExtension + "@^" + fileUrl + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + objectdocinfoid);
            }
        }

        /// <summary>
        /// 从75上下载热表文件并推送
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="toAppId"></param>
        /// <param name="objectdocinfoid"></param>
        public void RbDownloadFileFrom75(string fileUrl, string toAppId, string objectdocinfoid)
        {
            var absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\rb\\";
            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(absolutePath);
            }
            string fileNameWithExtension = Path.GetFileName(fileUrl);
            var path = absolutePath + fileNameWithExtension;
            //先从10.7.15.75文件服务器下载文件到本地，再上传给数据中心
            try
            {
                WebClient client = new WebClient();
                byte[] bytes = client.DownloadData(mesPathUrl + fileUrl);
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(bytes, 0, bytes.Length);
                }
                LogHelp.WriteLog("75原始地址【" + fileUrl + "】新地址：" + path);
                ExcuteFile(path, fileUrl, toAppId, "sendfiles", objectdocinfoid, "1");
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("【" + fileUrl + "】文件下载异常：" + ex.Message);
                LogHelp.WriteOrcale("文件下载异常" + "@^" + fileNameWithExtension + "@^" + fileUrl + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + objectdocinfoid);
            }
        }

        /// <summary>
        /// 从QMS上下载委托计量的附件并推送（entrustmeasurement表的附件都可以用这个方法）
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="toAppId"></param>
        /// <param name="objectdocinfoid"></param>
        public void DownloadFileFromQMS(DataRow drObject, string toAppId)
        {
            var absolutePath = AppDomain.CurrentDomain.BaseDirectory + "files\\qms\\";
            if (!Directory.Exists(absolutePath))
            {
                Directory.CreateDirectory(absolutePath);
            }
            string fileNameWithExtension = Path.GetFileName(drObject["fileName"].ToString());
            var path = absolutePath + fileNameWithExtension;
            //先从QMS文件服务器下载文件到本地，再上传给数据中心
            try
            {
                WebClient client = new WebClient();
                byte[] bytes = client.DownloadData(qmsPathUrl + drObject["filepath"].ToString());
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(bytes, 0, bytes.Length);
                }
                LogHelp.WriteLog("理化原始地址参数【" + drObject["filepath"].ToString() + "】新地址：" + path);
                ExcuteFile(path, drObject["filepath"].ToString(), toAppId, "sendfiles", drObject["objectdocinfoid"].ToString());
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("【" + drObject["filepath"].ToString() + "】文件下载异常：" + ex.Message);
                LogHelp.WriteOrcale("文件下载异常" + "@^" + fileNameWithExtension + "@^" + drObject["filepath"].ToString() + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + drObject["objectdocinfoid"].ToString());
            }
        }

        /// <summary>
        /// 判断该附件是否是其他表的附件
        /// </summary>
        /// <param name="objectDocId"></param>
        /// <returns></returns>
        private bool IsObjectDocInfoParent(DataRow drObject, string toAppId)
        {
            /*判断是否是热表厂推送的附件通知*/
            if (drObject["parentid"].ToString() == rbFactoryID)
            {
                RbDownloadFileFrom75(drObject["filepath"].ToString(), toAppId, drObject["objectdocinfoid"].ToString());//热表附件推送
                return false;
            }
            /*判断是否是委托数据的附件*/
            string sql = string.Format(@"SELECT e.ReportUrl FROM entrustmeasurement e WHERE e.entrustmeasurementid = '{0}'", drObject["parentid"].ToString());
            DataTable dtEntrust = OracleHelper.QueryTable(sql, null);
            if (dtEntrust.Rows.Count > 0 && dtEntrust.Rows[0]["ReportUrl"].ToString() == drObject["filepath"].ToString())
            {
                DownloadFileFromQMS(drObject, toAppId);//热表理化委托计量附件推送
                return false;
            }
            return true;
        }


        //表结构上传更换方法 以处理汉字乱码
        //public static string Post(string Url, string jsonParas)
        //{
        //    string strURL = Url;
        //    //创建一个HTTP请求
        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
        //    //Post请求方式
        //    request.Method = "POST";
        //    //内容类型
        //    request.ContentType = "application/json";

        //    //设置参数，并进行URL编码

        //    string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);

        //    //将Json字符串转化为字节
        //    byte[] payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);

        //    //设置请求的ContentLength
        //    request.ContentLength = payload.Length;
        //    //发送请求，获得请求流

        //    Stream writer;
        //    try
        //    {
        //        writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
        //    }
        //    catch (Exception)
        //    {
        //        writer = null;
        //        Console.Write("连接服务器失败!");
        //    }
        //    //将请求参数写入流
        //    writer.Write(payload, 0, payload.Length);
        //    writer.Close();//关闭请求流
        //    // String strValue = "";//strValue为http响应所返回的字符流
        //    HttpWebResponse response;
        //    try
        //    {
        //        //获得响应流
        //        response = (HttpWebResponse)request.GetResponse();
        //        Stream s = response.GetResponseStream();
        //        //  Stream postData = Request.InputStream;
        //        StreamReader sRead = new StreamReader(s);
        //        string postContent = sRead.ReadToEnd();
        //        sRead.Close();
        //        return postContent;//返回Json数据
        //    }
        //    catch (WebException ex)
        //    {
        //        response = ex.Response as HttpWebResponse;
        //        return "error";
        //    }

        //}

        //表数据上传
        public void Excute()
        {
            var settings = new JsonSerializerSettings
            {
                Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } }
            };
            try
            {
                var strSql = @"select distinct st.tablename,st.uniquecolname,ss.toappid,c5.customobjectitemsdesc qcr,
                        	c6.customobjectitemsdesc spr,c7.customobjectitemsdesc qfr
                        	from sync_tableinfo st 
 						    left join sync_tablechangerecord st2 on st2.tablename =st.tablename 
 						    left join sync_sendtoappid ss on ss.parentid =st2.id 
 						    left join customobjectitems c4 on  c4.customobjectitemsdesc=ss.toappid--不为空
                        	left join customobjectitems c5 on c5.customobjectid =c4.customobjectid and c5.customobjectitemsname='起草人'--不为空
                        	left join customobjectitems c6 on c6.customobjectid =c4.customobjectid and c6.customobjectitemsname='审批人'--不为空
                        	left join customobjectitems c7 on c7.customobjectid =c4.customobjectid and c7.customobjectitemsname='签发人'--不为空
 						    where st.ismeshandle='1' and ss.ismeshandle ='0' -- and st.tablename='OBJECTDOCINFO'
                            order by ss.toappid,st.tablename";
                var updateSql = @"update sync_sendtoappid set ISMESHANDLE = 1,businessid = '{0}',sendtime = SYSDATE where ID in ('{1}')";
                DataTable myDt = OracleHelper.QueryTable(strSql, null);
                foreach (DataRow row in myDt.Rows)
                {
                    Dictionary<string, string> resDic = new Dictionary<string, string>();
                    string toAppId = row["toappid"].ToString();
                    var tableData = getTableDataByTableName(row["tablename"].ToString(), row["uniquecolname"].ToString(), toAppId);
                    if (row["tablename"].ToString().Equals("OBJECTDOCINFO") && tableData.Rows.Count > 0)
                    { //特殊处理、如果表是工艺附件存储表
                        Parallel.ForEach(tableData.Select(), item =>
                        {
                            if (IsObjectDocInfoParent(item, toAppId))//如果不存在是其他表的附件，则就是工艺附件
                            {
                                DownloadFileFrom76(item["filepath"].ToString(), toAppId, item["objectdocinfoid"].ToString());//工艺附件推送
                            }
                        });
                    }
                    var tableDataCopy = tableData.Copy();
                    if (tableData.Rows.Count > 0)
                    {
                        tableData.Columns.Remove("STID");//移除不需要传递的数据列
                        Dictionary<string, object> para = new Dictionary<string, object>();
                        para.Add("fromappid", toDataCenterAppid);
                        para.Add("toappid", toAppId);
                        para.Add("trantype", "10");
                        para.Add("updtype", "10");
                        para.Add("tablename", row["tablename"].ToString().ToUpper());

                        para.Add("wenjianqicaoren", string.IsNullOrWhiteSpace(row["qcr"].ToString()) ? "刘美美" : row["qcr"].ToString());//起草人
                        para.Add("shenpiren", string.IsNullOrWhiteSpace(row["spr"].ToString()) ? "刘美美" : row["spr"].ToString());//审批人
                        para.Add("qianfaren", string.IsNullOrWhiteSpace(row["qfr"].ToString()) ? "刘美美" : row["qfr"].ToString());//签发人

                        para.Add("items", new object[0]);
                        DataTable tableNewData = tableData.AsEnumerable().GroupBy(p => new { id = p["id"].ToString(), prostatus = p["prostatus"].ToString() }).Select(p => p.First()).CopyToDataTable();//去重
                        String tableJson = JsonConvert.SerializeObject(tableNewData, settings);
                        //GZip压缩方式
                        //byte[] compressedJson = encryptHelper.CompressString(jsonString);
                        //Console.WriteLine("压缩后的JSON字符串（Base64编码）： " + Convert.ToBase64String(compressedJson));

                        String jsonString = "";
                        //增加逻辑，如果查询结果超过1万条，执行压缩,每次查询结果限定为10万条       
                        //采用gzip压缩方式         
                        para.Add("iszip", "1");
                        para.Add("ziptype", "gzip");
                        para.Add("zipdata", EncryptHelper.CompressString(tableJson));
                        jsonString = JsonConvert.SerializeObject(para, settings);
                        //存为文件
                        //String filePath = @"c:\" + row["tablename"].ToString() + DateTime.Now.ToString("yyyy-MM-ddHHmmss") + ".json";
                        //File.WriteAllText(filePath, jsonString);
                        //数据量超过3万时写入缓慢，正式时可以考虑去掉或简化
                        LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】开始推送数据：记录数" + tableData.Rows.Count);
                        var result = HttpUtils.Post(tableDataUrl, jsonString);

                        LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】推送返回结果：" + result);
                        resDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                    }
                    var ids = string.Empty;
                    int i = 0;
                    foreach (DataRow rowt in tableDataCopy.Rows)
                    {
                        if (i < 999)
                        {
                            ids += rowt["stid"] + ",";
                        }
                        else
                        {
                            if (!String.IsNullOrWhiteSpace(ids))
                            {
                                OracleHelper.ExecuteSql(string.Format(updateSql, resDic["result"], ids.TrimEnd(',').Replace(",", "','")));
                            }
                            ids = rowt["stid"] + ",";
                            i = 0;
                        }
                        i++;
                    }
                    if (!String.IsNullOrWhiteSpace(ids))
                    {
                        OracleHelper.ExecuteSql(string.Format(updateSql, resDic["result"], ids.TrimEnd(',').Replace(",", "','")));
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("表数据推送异常：" + ex.Message);
            }
        }

        //表数据上传（热表主数据）
        public void ExcuteRB()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                Converters = { new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } }
            };
            try
            {
                string strSql = string.Format(@"select distinct st.tablename,st.uniquecolname,c5.customobjectitemsdesc qcr,
                          c6.customobjectitemsdesc spr,c7.customobjectitemsdesc qfr
                          from sync_tableinfo st 
                          left join sync_tablechangerecord_rb st2 on st2.tablename =st.tablename 
                          left join customobjectitems c4 on  c4.customobjectitemsdesc = '{0}'--不为空
                          left join customobjectitems c5 on c5.customobjectid =c4.customobjectid and c5.customobjectitemsname='起草人'--不为空
                          left join customobjectitems c6 on c6.customobjectid =c4.customobjectid and c6.customobjectitemsname='审批人'--不为空
                          left join customobjectitems c7 on c7.customobjectid =c4.customobjectid and c7.customobjectitemsname='签发人'--不为空
                          where st.ismeshandle='1' and st2.ismeshandle ='0'
                          order by st.tablename", toAppId_rb);
                DataTable myDt = OracleHelper.QueryTable(strSql, null);
                foreach (DataRow row in myDt.Rows)
                {
                    Dictionary<string, string> resDic = new Dictionary<string, string>();//接口返回参数
                    DataTable tableData = GetRBTableDataByTableName(row["tablename"].ToString(), row["uniquecolname"].ToString());//获取可推送的表数据
                    if (row["tablename"].ToString().Equals("OBJECTDOCINFO") && tableData.Rows.Count > 0)
                    { //特殊处理、如果表是工艺附件存储表
                        Parallel.ForEach(tableData.Select(), item =>
                        {
                            DownloadFileFrom76(item["filepath"].ToString(), toAppId_rb, item["objectdocinfoid"].ToString());//工艺附件推送
                        });
                    }
                    var tableDataCopy = tableData.Copy();
                    if (tableData.Rows.Count > 0)
                    {
                        Dictionary<string, object> para = new Dictionary<string, object>();
                        para.Add("fromappid", toDataCenterAppid);
                        para.Add("toappid", toAppId_rb);
                        para.Add("trantype", "10");
                        para.Add("updtype", "10");
                        para.Add("tablename", row["tablename"].ToString().ToUpper());

                        para.Add("wenjianqicaoren", string.IsNullOrWhiteSpace(row["qcr"].ToString()) ? "刘美美" : row["qcr"].ToString());//起草人
                        para.Add("shenpiren", string.IsNullOrWhiteSpace(row["spr"].ToString()) ? "刘美美" : row["spr"].ToString());//审批人
                        para.Add("qianfaren", string.IsNullOrWhiteSpace(row["qfr"].ToString()) ? "刘美美" : row["qfr"].ToString());//签发人

                        para.Add("items", new object[0]);
                        DataTable tableNewData = tableData.AsEnumerable().GroupBy(p => new { id = p["id"].ToString(), prostatus = p["prostatus"].ToString() }).Select(p => p.First()).CopyToDataTable();//去重
                        String tableJson = JsonConvert.SerializeObject(tableNewData, settings);
                        //GZip压缩方式
                        //byte[] compressedJson = encryptHelper.CompressString(jsonString);
                        //Console.WriteLine("压缩后的JSON字符串（Base64编码）： " + Convert.ToBase64String(compressedJson));

                        String jsonString = "";
                        //增加逻辑，如果查询结果超过1万条，执行压缩,每次查询结果限定为10万条       
                        //采用gzip压缩方式         
                        para.Add("iszip", "1");
                        para.Add("ziptype", "gzip");
                        para.Add("zipdata", EncryptHelper.CompressString(tableJson));
                        jsonString = JsonConvert.SerializeObject(para, settings);
                        //存为文件
                        //String filePath = @"c:\" + row["tablename"].ToString() + DateTime.Now.ToString("yyyy-MM-ddHHmmss") + ".json";
                        //File.WriteAllText(filePath, jsonString);
                        //数据量超过3万时写入缓慢，正式时可以考虑去掉或简化
                        LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】开始推送数据：记录数" + tableData.Rows.Count);
                        var result = HttpUtils.Post(tableDataUrl, jsonString);

                        LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】推送返回结果：" + result);
                        resDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(result);
                    }
                    string ids = string.Empty;
                    string updateSql = @"UPDATE sync_tablechangerecord_rb st SET st.ismeshandle = 1,st.businessid = '{0}',st.sendtime = SYSDATE 
                                         WHERE st.id = '{1}'";
                    foreach (DataRow rowt in tableDataCopy.Rows)
                    {
                        OracleHelper.ExecuteSql(string.Format(updateSql, resDic["result"], rowt["stid"].ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("表数据推送异常：" + ex.Message);
            }
        }

        //表结构获取
        public void GetTableDef()
        {
            var strSql = @"select * from sync_tableinfo st  where st.ismeshandle='1'";
            DataTable myDt = OracleHelper.QueryTable(strSql, null);
            foreach (DataRow row in myDt.Rows)
            {
                string tablename = row["tablename"].ToString();
                var result = HttpUtils.Post(getTableDefurl + "?appid=" + toDataCenterAppid + "&tablename=" + tablename, "{}");
                LogHelp.WriteLog("表【" + tablename + "】数据中心表结构查询返回结果：" + result);
            }
        }

        //表数据获取
        public void GetTableData()
        {
            var strSql = @"select * from sync_tableinfo st  where st.ismeshandle='1'";
            DataTable myDt = OracleHelper.QueryTable(strSql, null);
            foreach (DataRow row in myDt.Rows)
            {
                string tablename = row["tablename"].ToString();
                var result = HttpUtils.Post(getTableDataUrl + "?appid=" + toDataCenterAppid + "&tablename=" + tablename + "&pageNo=1&pageSize=10", "{}");
                LogHelp.WriteLog("表【" + tablename + "】数据中心表数据查询返回结果：" + result);
            }
        }


        //表结构上传
        public void ExcuteTableDef()
        {
            try
            {
                var strSql = @"select * from sync_tableinfo st where  st.ismeshandle='0' --and tablename=upper('objectdocinfo')";
                DataTable myDt = OracleHelper.QueryTable(strSql, null);
                foreach (DataRow row in myDt.Rows)
                {
                    var tbdefSQL = @"select distinct t.column_name,s.data_type, t.comments,to_char(s.column_id) column_id,nullable,s.char_col_decl_length,
                        	    case when s.data_type='NVARCHAR2' or s.data_type='NCHAR' then to_char(s.char_col_decl_length) else to_char(s.data_length) end data_length,
                                case t.column_name  when(select col.column_name from user_constraints con,user_cons_columns col
									where con.constraint_name=col.constraint_name and con.constraint_type='P'
									and col.table_name='{0}') then '1'else '0' end as iskey
                                from user_col_comments t, user_tab_columns s 
                                where t.table_name ='{0}' and s.table_name ='{0}'
                                and t.column_name = s.column_name
                                order by t.column_name";
                    var tableDef = OracleHelper.QueryTable(string.Format(tbdefSQL, row["tablename"].ToString()), null);
                    var list = new ArrayList();
                    Dictionary<string, Object> item = new Dictionary<string, Object>();
                    foreach (DataRow trow in tableDef.Rows)
                    {
                        item = new Dictionary<string, Object>();
                        item.Add("fieldname", trow["column_name"]);
                        item.Add("fieldtype", trow["data_type"]);
                        item.Add("fieldcn", trow["comments"]);
                        item.Add("fieldlen", trow["data_length"].ToString());
                        item.Add("iskey", "0");//trow["iskey"]);
                        item.Add("isnull", trow["nullable"].Equals("Y") ? "1" : "0");
                        item.Add("orderindex", trow["column_id"]);
                        list.Add(item);
                    }

                    //没有id列时，新增id列
                    //if (!item.ContainsValue("ID") && (trow["iskey"].Equals("1") || trow["column_name"].Equals(row["uniquecolname"].ToString())))
                    if (tableDef.Select("column_name='ID'").Length == 0)
                    {
                        Dictionary<string, Object> itemID = item.ToDictionary(pair => pair.Key, pair => pair.Value);
                        itemID["fieldname"] = "ID";
                        itemID["iskey"] = "1";
                        itemID["fieldtype"] = "VARCHAR2";
                        itemID["fieldlen"] = "40";
                        itemID["isnull"] = "1";
                        list.Add(itemID);
                    }

                    item = new Dictionary<string, Object>();
                    item.Add("fieldname", "PROSTATUS");
                    item.Add("fieldtype", "VARCHAR2");
                    item.Add("fieldcn", "");
                    item.Add("fieldlen", "1");
                    item.Add("iskey", "0");
                    item.Add("isnull", "1");
                    list.Add(item);

                    Dictionary<string, object> para = new Dictionary<string, object>();
                    para.Add("fromappid", toDataCenterAppid);
                    para.Add("toappid", toAppId_rb);
                    para.Add("trantype", "10");
                    para.Add("updtype", "10");
                    para.Add("tablename", row["tablename"].ToString().ToUpper());
                    para.Add("tablecn", "");
                    para.Add("fields", list);
                    para.Add("wenjianqicaoren", "刘美美");//起草人
                    para.Add("shenpiren", "刘美美");//审批人
                    para.Add("qianfaren", "刘美美");//签发人
                    string json = JsonConvert.SerializeObject(para); //System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(para));
                    LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】结构开始推送：" + json);
                    //var result = Post(tableDefurl, json);                    
                    var result = HttpUtils.Post(tableDefurl, json);
                    LogHelp.WriteLog("表【" + row["tablename"].ToString() + "】结构推送返回结果：" + result);
                    Dictionary<string, object> existTableDef = JsonConvert.DeserializeObject<Dictionary<string, object>>(result);
                    if ((existTableDef.ContainsKey("success") && existTableDef["success"].ToString().ToLower().Equals("true")) || existTableDef["message"].ToString().Equals("已存在同名表结构"))
                    {
                        OracleHelper.ExecuteSql(string.Format("update sync_tableinfo set ismeshandle='1' where tablename='{0}'", row["tablename"].ToString().ToUpper()));
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelp.WriteLog("表结构数据推送异常：" + ex.Message);
            }

        }


        /// <summary>
        /// 获取对应表（新增）数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="uniqueColName">表列名(主键)</param>
        /// <returns></returns>
        public DataTable getTableDataByTableName(string tableName, string uniqueColName, string toAppId)
        {
            try
            {
                var strSql = @"select st.uniquecolvalue as id,decode(st.operatetype,1,'A',2,'U','D') prostatus,ss.id as stid ,t.* from sync_tablechangerecord st
                left join {0} t on t.{1} =st.uniquecolvalue
                left join  sync_sendtoappid ss on ss.parentid=st.id
                where st.tablename ='{0}' and ss.ismeshandle =0 and ss.toappid='{2}'";
                strSql += String.Format(" and rownum<{0}", perRows);
                DataTable myDS = OracleHelper.QueryTable(string.Format(strSql, tableName, uniqueColName, toAppId), null);
                return myDS;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// 获取对应表（新增）数据（热表） add by zhangrj 20250728
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="uniqueColName">表列名(主键)</param>
        /// <returns></returns>
        public DataTable GetRBTableDataByTableName(string tableName, string uniqueColName)
        {
            try
            {
                var strSql = @"select st.id as stid,st.uniquecolvalue as id,decode(st.operatetype,1,'A',2,'U','D') prostatus,t.* from sync_tablechangerecord_rb st
                left join {0} t on t.{1} = st.uniquecolvalue
                where st.tablename ='{0}' and st.ismeshandle = 0";
                strSql += String.Format(" and rownum < {0}", perRows);
                DataTable myDS = OracleHelper.QueryTable(string.Format(strSql, tableName, uniqueColName), null);
                return myDS;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}
